<?php

require_once 'SmartL/Zend/Controller/Action.php';
require_once 'Zend/Form.php';
require_once 'SmartL/DataBinder.php';
require_once 'SmartL/Zend/Form.php';
require_once 'Db/Shop/Record/User.php';

class UserController extends SmartL_Zend_Controller_Action
{
    /**
     * User login.
     * Parameters: username, password
     */
    public function loginAction()
    {
        $form = SmartL_Zend_Form::getForm($this->config->getAction("login")->getForm("login"), $this->translations['default']);
        $this->view->form = $form;

        if ( isset($_POST['loginAction']) ) {
        	$result = Demo_Login::getLoginResult();
        	//form is send
        	if ( $form->isValid($_POST) and isset($result) and $result->isValid() ) {
				//if it is valid
				return;
			}
        	$data = $_POST;
        	unset($data['password']);
        	$form->populate($data);
        	if ( isset($result) ) $this->view->loginResult = $result;
        }
    }

    /**
     * User registration.
     * Parameters: username, password, full name, language, address, email
     */
    public function registerAction()
    {
        $form = SmartL_Zend_Form::getForm($this->config->getAction('register')->getForm('register'),
        					$this->translations['default']);
        $this->view->form = $form;

        if ( isset($_POST['registerAction']) ) {

        	if ( $form->isValid($_POST) ) {
        		//save user
        		$user = new Db_Shop_Record_User();
        		SmartL_DataBinder::update($form, 'zendForm', $user, 'doctrine',
        			array("username","password","fullName","email","address"));
        		$user->languageId = $this->application->getDefaultLanguage()->getId();
        		$user->templateId = $this->application->getActualTemplate()->getName();
        		$user->skinId = $this->application->getActualTemplate()->getActualSkin();
        		$user->save();

        		$this->_helper->viewRenderer->renderScript('user/register-ok.phtml');
        		return;
        	}
        	$data = $_POST;
        	unset($data['password']);
        	unset($data['password2']);
        	$form->populate($_POST);
        }
    }

    /**
     * User settings.
     * Parameters: username, password, full name, address, email, skin, template + *user
     */
    public function settingsAction()
    {
    	$user = Zend_Auth::getInstance()->getIdentity();
        if (empty($user)) {
            $this->_helper->redirector->goto("index","index");
        }

        $form = SmartL_Zend_Form::getForm($this->config->getAction('settings')->getForm('settings'),$this->translations['default']);
        $this->view->form = $form;

		$binder = new SmartL_DataBinder($user,'doctrine',$form,'zendForm',
			array("username","email","fullName","address",
			"languageId"=>"selectLanguage","templateId"=>"selectTemplate","skinId"=>"selectSkin"));

        //languages
        foreach ($this->application->getSupportedLanguages() as $lang) {
	      	$languages[$lang->getId()] = $lang->getLanguageName()."-".$lang->getCultureName();
	    }
	    $form->getElement('selectLanguage')->options = $languages;
	    //templates
	    foreach ($this->application->getTemplates() as $template) {
	    	$templates[$template->getName()] = $template->getName();
	    }
	    $form->getElement('selectTemplate')->options = $templates;
	    //skins
	    foreach ($this->application->getActualTemplate()->getSkins() as $skin ) {
	    	$skins[$skin]=$skin;
	    }
	    $form->getElement('selectSkin')->options = $skins;
	    $form->selectSkin->setRegisterInArrayValidator(false);


	    //form validation
        if ( isset($_POST['settingsAction']) ) {
        	if ( $form->isValid($_POST) ) {

        	    $tplBefore = $user->templateId;
        	    $skinBefore = $user->skinId;

        	    //validate skin name
        	    $template = $this->application->getTemplates();
        	    $template = $template[$form->selectTemplate->getValue()];
        	    if ( isset($template) ) {
        	    	$skins = $template->getSkins();
        	    	if ( array_search($form->selectSkin->getValue(), $skins) === null ) {
        	    		$form->selectSkin->setValue($template->getActualSkin());
        	    	}
        	    }
        	    else {
        	    	$form->selectTemplate->setValue($this->application->getActualTemplate()->getName());
        	    	$form->selectSkin->setValue($this->application->getActualTemplate()->getActualSkin());
        	    }

				$binder->updateBusinessObject();
        		$user->save();
        		Zend_Auth::getInstance()->getStorage()->clear();
        		Zend_Auth::getInstance()->getStorage()->write($user);

        		// To redirect correctly, we must change actual language
        		$newLang = new SmartL_Application_Config_LanguageInfo($form->getValue('selectLanguage'));
        		$this->application->setUserLanguageWithDefaultCulture($newLang);

        		// To show user the index page with info about templates and skins (if he changed them)
        		if ($user->templateId !== $tplBefore or $user->skinId !== $skinBefore) {
        		  $this->_helper->redirector->goto("index","index");
        		}
        	}
        }
        else {
        	$binder->updateUIObject();
        }
    }

    /**
     * Get avaiable skins for given template.
     * Parameters: template id, *user
     */
    public function skinsAjaxRequestAction() {
    	if ( $this->_hasParam("template") ) {
    		$templates = $this->application->getTemplates();
    		$template = $templates[$this->_getParam("template")];
    		$this->_helper->json->direct($template->getSkins());
    	}
    }

    /**
     * User logout.
     * Parameters: *user
     */
    public function logoutAction() {
    	if ( Zend_Auth::getInstance()->getIdentity() ) {
    		Zend_Auth::getInstance()->clearIdentity();
    		$this->_helper->redirector->goto('index','index');
    	}
    }
}
